package com.zbkj.crmeb.config;

import com.interceptor.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.MappedInterceptor;

import com.crmeb.core.interceptor.SwaggerInterceptor;
import com.filter.ResponseFilter;
import com.utils.UploadConfig;

//token验证拦截器

@Configuration
public class WebConfig implements WebMvcConfigurer {

    // 这里使用一个Bean为的是可以在拦截器中自由注入，也可以在拦截器中使用SpringUtil.getBean 获取
    // 但是觉得这样更优雅

    @Bean
    public HandlerInterceptor adminAuthInterceptor(){
        return new AdminAuthInterceptor();
    }
    @Bean
    public HandlerInterceptor operationAuthInterceptor(){ return new OperationAuthInterceptor(); }

/*
    @Bean
    public CorsInterceptor corsInterceptor(){
        return new CorsInterceptor();
    }*/

    @Bean
    public HandlerInterceptor adminTokenInterceptor(){
        return new AdminTokenInterceptor();
    }

    @Bean
    public HandlerInterceptor frontTokenInterceptor(){
        return new FrontTokenInterceptor();
    }


    @Bean
    public HandlerInterceptor openSpiTokenInterceptor(){
        return new OpenApiTokenInterceptor();
    }

    @Bean
    public ResponseFilter responseFilter(){ return new ResponseFilter(); }

    @Value("${swagger.basic.username}")
    private String username;
    @Value("${swagger.basic.password}")
    private String password;
    @Value("${swagger.basic.check}")
    private Boolean check;


  @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加token拦截器
        //addPathPatterns添加需要拦截的命名空间；
        //excludePathPatterns添加排除拦截命名空间


        //后台token拦截
      registry.addInterceptor(adminTokenInterceptor()).
              addPathPatterns("/api/admin/**").
              addPathPatterns("/api/chant/**").
              excludePathPatterns("/api/admin/validate/**").
              excludePathPatterns("/api/admin/login").
              excludePathPatterns("/api/admin/logout").
              excludePathPatterns("/api/admin/getLoginPic").
              excludePathPatterns("/api/admin/payment/callback/**").
              excludePathPatterns("/api/admin/upload/oss/image/**").
              excludePathPatterns("/api/admin/system/attachment/**").
              excludePathPatterns("/api/admin/getAdminInfoByToken/**").
              excludePathPatterns("/api/admin/code").
              excludePathPatterns("/api/admin/forgetPwd").
              excludePathPatterns("/api/admin/register").
              excludePathPatterns("/api/admin/saveInfo").
              excludePathPatterns("/api/admin/register/code").
              excludePathPatterns("/api/admin/category/mainCategory").
              excludePathPatterns("/api/admin/mer/group/productId/**").
              excludePathPatterns("/api/admin/supplier/business/apply/**").
              excludePathPatterns("/api/admin/supplier/open/shop/**").
              excludePathPatterns("/api/admin/key/value/listByTypeCode/**").
              excludePathPatterns("api/admin/store/order/manual/select/push").
              excludePathPatterns("/upload/**", "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");

        //后台权限规则
        registry.addInterceptor(adminAuthInterceptor()).
                addPathPatterns("/api/admin/**").
                addPathPatterns("/api/chant/**").
                excludePathPatterns("/api/admin/validate/**").
                excludePathPatterns("/api/admin/login").
                excludePathPatterns("/api/admin/logout").
                excludePathPatterns("/api/admin/getLoginPic").
                excludePathPatterns("/api/admin/payment/callback/**").
                excludePathPatterns("/api/admin/getAdminInfoByToken/**").
                excludePathPatterns("/api/admin/mer/group/productId/**").
                excludePathPatterns("/api/admin/supplier/business/apply/**").
                excludePathPatterns("/api/admin/supplier/open/shop/**").
                excludePathPatterns("/api/admin/key/value/listByTypeCode/**").
                excludePathPatterns("api/admin/store/order/manual/select/push").
//                excludePathPatterns("/api/admin/store/product/**").
                excludePathPatterns("/upload/**","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");


      //后台权限规则
      registry.addInterceptor(operationAuthInterceptor()).
              addPathPatterns("/api/admin/**").
              excludePathPatterns("/api/admin/validate/**").
              excludePathPatterns("/api/admin/login").
              excludePathPatterns("/api/admin/logout").
              excludePathPatterns("/api/admin/getLoginPic").
              excludePathPatterns("/api/admin/payment/callback/**").
              excludePathPatterns("/api/admin/getAdminInfoByToken/**").
              excludePathPatterns("/api/admin/mer/group/productId/**").
              excludePathPatterns("api/admin/store/order/manual/select/push").
              excludePathPatterns("/api/admin/supplier/open/shop/**").
              excludePathPatterns("/api/admin/key/value/listByTypeCode/**").
              excludePathPatterns("/api/admin/supplier/business/apply/**").
//                excludePathPatterns("/api/admin/store/product/**").
        excludePathPatterns("/upload/**","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");


        //前端用户登录token
        registry.addInterceptor(frontTokenInterceptor()).
                addPathPatterns("/api/front/**").
                // addPathPatterns("/api/admin/supplier/business/apply/**").
                excludePathPatterns("/api/front/qrcode/**").
                excludePathPatterns("/api/front/login/mobile").
                excludePathPatterns("/api/front/login").
                excludePathPatterns("/api/front/sendCode").
                excludePathPatterns("/api/front/wechat/**").
                excludePathPatterns("/api/front/search/keyword").
                excludePathPatterns("/api/front/share").
                excludePathPatterns("/api/front/article/**").
                excludePathPatterns("/api/front/city/**").
                excludePathPatterns("/api/front/product/hot").
                excludePathPatterns("/api/front/products/**").
                excludePathPatterns("/api/front/brand/**").
                excludePathPatterns("/api/front/reply/**").
                excludePathPatterns("/api/front/user/service/**").
                excludePathPatterns("/api/front/logistics").
                excludePathPatterns("/api/front/product/noauth/detail/**").
                excludePathPatterns("/api/front/groom/list/**").
                excludePathPatterns("/api/front/index").
                excludePathPatterns("/api/front/category").
                excludePathPatterns("/api/admin/upload/image/**").
                addPathPatterns("/api/front/mer/**").
                excludePathPatterns("/api/front/mer/qrcode/**").
                excludePathPatterns("/api/front/mer/login/mobile").
                excludePathPatterns("/api/front/mer/login").
                excludePathPatterns("/api/front/mer/sendCode").
                excludePathPatterns("/api/front/mer/wechat/**").
                excludePathPatterns("/api/front/mer/search/keyword").
                excludePathPatterns("/api/front/mer/share").
                excludePathPatterns("/api/front/mer/article/**").
                excludePathPatterns("/api/front/mer/city/**").
                excludePathPatterns("/api/front/mer/product/hot").
//                excludePathPatterns("/api/front/mer/products/**").
                excludePathPatterns("/api/front/mer/brand/**").
                excludePathPatterns("/api/front/mer/reply/**").
                excludePathPatterns("/api/front/mer/user/service/**").
                excludePathPatterns("/api/front/mer/logistics").
//                excludePathPatterns("/api/front/mer/product/noauth/detail/**").
                excludePathPatterns("/api/front/mer/groom/list/**").
//                excludePathPatterns("/api/front/mer/index").
                excludePathPatterns("/api/front/mer/category").
                excludePathPatterns("/api/admin/mer/upload/image/**").
//                excludePathPatterns("/api/front/mer/product/listByIds").
                excludePathPatterns("/api/front/mer/getRuleByCate").
                excludePathPatterns("/api/front/getMerIdByPhone").
                excludePathPatterns("/api/front/login/loginByPhoneAndMerId").
                excludePathPatterns("/api/front/login/validateCode").
                excludePathPatterns("/api/admin/mer/group/productId/**").
                excludePathPatterns("api/admin/store/order/manual/select/push").
                excludePathPatterns("api/admin/supplier/open/shop/**").
                excludePathPatterns("/api/admin/key/value/listByTypeCode/**").
                //excludePathPatterns("/api/front/prom/**").
//                excludePathPatterns("/api/front/cart/count").
                excludePathPatterns("/upload/**","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");

        //后台token拦截
       registry.addInterceptor(openSpiTokenInterceptor()).
                addPathPatterns("/api/open/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String os = System.getProperty("os.name");

        //Windows
        if(os.toLowerCase().startsWith("win")) {
            registry.addResourceHandler("/upload/**")
                    .addResourceLocations("file:"+UploadConfig.getFilePathWindow());
        //linux
        }else{
            registry.addResourceHandler("/upload/**")
                    .addResourceLocations("file:"+UploadConfig.getFilePathLinux());
        }
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Bean
    public FilterRegistrationBean filterRegister()
    {
        //注册过滤器
        FilterRegistrationBean registration = new FilterRegistrationBean(responseFilter());
        registration.addUrlPatterns("/**");
        return registration;
    }

    // 必须在此处配置拦截器,要不然拦不到swagger的静态资源
    @Bean
    @ConditionalOnProperty(name = "swagger.basic.enable", havingValue = "true")
    public MappedInterceptor getMappedInterceptor() {
        return new MappedInterceptor(new String[]{"/upload/**","/swagger-ui.html", "/webjars/**"}, new SwaggerInterceptor(username, password, check));
    }
    // 验证参数是否完全匹配
//    @Override
//    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//        WebMvcConfigurer.super.configureMessageConverters(converters);
//        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(getObjectMapper());
//        converters.add(jackson2HttpMessageConverter);
//    }
//    @Bean
//    public ObjectMapper getObjectMapper() {
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
//        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//        return mapper;
//    }
}
